  //获取应用实例
let app = getApp();
let FormCheckRule = {
	sendAddressNullMessage: '请选择上门揽件详细地址',
	collectAddressNullMessage: '请选择收件人详细地址',
	checkService: '请阅读并同意《国内特快专递承诺服务免责条款》',
	hkCheckService: '请阅读并同意《香港快递承诺条款》'
};
var isShowRender = true;
Page({
	data: {
		imgUrls: '',
		isShowImg: false,
		sendTypeName: '普通快递', //寄送类型
		sendType: 1,
		isShowSendTypeList: false, 
		sendTypeData: [   //取证方式
			{times: 1, timesName: "普通快递",},
			{times: 2, timesName: "香港快递"}
		],
		goodsTypeName: '文件',
		goodsType: '01',
		isShowGoodsTypeList: false, 
		goodsData: [
			{times: '01', timesName: "文件",},
			// {times: '02', timesName: "数码产品"},
			// {times: '03', timesName: "生活用品",},
			// {times: '04', timesName: "校园包裹"},
			{times: '05', timesName: "物品",}
		],
		needInvoice: 1,  //是否勾选
    	isCanScroll: true, //屏幕是否能够滑动
		isShowFootNav: true,  //底部导航菜单
		isShowModal: false,
		isSHowWaybillMask: false, //从新扫描蒙层
		focus: false, //textarea焦点
		leaveText: '', //留言
		mailType: '',  //寄递类型 *区分寄或者收
		//寄
		sendAddressProvinceId: '', 
		sendAddressCityId: '',
		sendAddressCountyId: '',
		sendAddressContactName: '',
		sendAddressCellNum: '',
		sendAddressStreet: '',
		sendAddressFullAddr: '',
		sendAddressMailboxNum: '',
		sendAddressPostCode: '',
		showSendMailboxNum: '', 
		//收
		collectAddressProvinceId: '',
		collectAddressCityId: '', 
		collectAddressCountyId: '',
		collectAddressContactName:  '',
		collectAddressCellNum: '',
		collectAddressStreet: '',
		collectAddressFullAddr: '',
		collectAddressMailboxNum: '',
		collectAddressPostCode: '',
		showCollectMailboxNum: '',
		num: 0  //订单数
	},

	//获得广告图片
	getAdvertisement() {
		let that = this;
		let advertOpt = {   //请求广告
			url: app.globalData.host + "/wx/sd/ad.ajax",
			data: {},
			sucFn:(result) => {
				let imgUrls = result.body;
				if (imgUrls.icon) {
					that.setData({
						imgUrls: imgUrls.icon,
						isShowImg: true
					})
				} else {
					that.setData({
						imgUrls: imgUrls,
						isShowImg: false
					})
				}
			}
		};
		app.ajax(advertOpt);
	},

	/**
	 * 获的原生地址信息
	 */
	toAddressList(e) {
		//send 寄  collect 收
		let type = e.currentTarget.dataset.type;
		this.setData({
			mailType: type
		})
		app.setStorageSync(app.globalData.cacheData,Object.assign({},this.data,
			{ popErrorMsg: '' },{errorFocusName:''}));

		let currentAddress = '';
		if (type == 'send') {
			currentAddress = this.data.sendAddressAll
		} else {
			currentAddress = this.data.collectAddressAll
		}
		app.setStorageSync('addressType',type)
		app.setStorageSync('selectedAddress',currentAddress)
		app.navigateTo({url:'../addressList/addressList'})
	},

	bindinput(e) {
		var value = e.detail.value;
		this.setData({
			leaveText: value
		})
	},

	bindButtonTap() {
		this.setData({
			focus: true
		})
	},
	
	//是否勾选协议
	checkTap(e) {
		let needInvoice = e.target.dataset.agree;
		if (needInvoice == 0) {
			needInvoice = 1;
		} else {
			needInvoice = 0;
		}
		this.setData({needInvoice: needInvoice});
	},

	   //条形码
	bindViewTap() {
        let that = this;
		// let path= /^[0-9a-zA-Z]*$/g;
        wx.scanCode({
            success:(res) => {
				setTimeout(() => {
					let bno = /[\?|&]bno=([^&]+)/g;
					bno = bno.exec(res.result);
					bno = bno ? bno[1] : '';
	
				
					that.checkLogisticsData(bno)
					that.setData({
						isSHowWaybillMask: false //隐藏蒙层
					});
				},500)
			}
        })
	},
	
	//隐藏蒙层
	hideWaybillMask() {
		this.setData({
			isSHowWaybillMask: false, //隐藏蒙层
			isShowFootNav: true
		})
	},

	clearEXpressNbr() {
		this.setData({
			isSHowWaybillMask: false, //隐藏蒙层
			isShowFootNav: true,
			expressNbr: ''
		})
	},

	//分享功能
	onShareAppMessage() {
		return {
			title: 'EMS寄快递办理',
			desc: 'EMS寄快递办理',
			path: '/pages/handle/handle'
		}
	},

	getOptionsParam(options) {
		/*
		*	参数
		*	bao 运单号
		*   scene 渠道号
		*/
		if (options.q) { 
			let link = decodeURIComponent(options.q),
				bno = /[\?|&]bno=([^&]+)/g,
				scene = /[\?|&]scene=([^&]+)/g,
				that = this;
            bno = bno.exec(link);
			bno = bno?bno[1] : '';
			scene = scene.exec(link);
			scene = scene?scene[1] : '';
			options['scene'] = scene

			this.checkLogisticsData(bno)
		} 
		app.globalData.channelId = decodeURIComponent(options.scene) != 'undefined'?
								decodeURIComponent(options.scene) : app.globalData.channelId ? 
								app.globalData.channelId:'';
			console.log("channelId",app.globalData.channelId);	
	},

	checkLogisticsData(bno) {
		let formResult = {
			comName: 'EMS',
			comNo: 'ems',
			inputValue: bno
		};
		let that = this;

		let opt = {
			url: app.globalData.host+"/wx/sd/queryEms.ajax",
			data: formResult,
			sucFn:(result) => {
				let infoList = result.body.infoList;
				if (infoList) {					
					formResult['infoList'] = infoList
					app.setStorageSync(app.globalData.checkProgress, formResult);
					app.navigateTo({url:'../checkProgress/checkProgress'})						
				} else {
					that.setData({
						expressNbr: bno
					})
				}
			}
		};
		app.ajax(opt);
	},

	checkData(e) {
		this.setData({
			expressNbr: e.detail.value
		})
	},

	setAddress() {
		var mailType = this.data.mailType,
			that = this,
			collectAddress = '',
			address = app.getStorageSync('currentEMSAddress');

			// 0：显示地址 1：显示邮筒号
			if (mailType == 'collect') { //收
				if (address) {
					// if (this.data.sendAddressAll&&this.data.sendAddressAll.id == address.id) {
					// 	app.errorToast('不能和寄件地址相同')
					// 	return;
					// }
					if (address.mailboxNumRule&&address.mailboxNumRule.showCollectMailboxNum == 1) {
						this.setData({
							collectAddressMailboxNum: address.mailboxNum
						})
					} else {
						this.setData({
							collectAddressMailboxNum: ''
						})
					}
					this.setData({
						collectAddressAll: address,
						collectAddressProvinceId: address.provinceId,
						collectAddressCityId: address.cityId, 
						collectAddressCountyId: address.countyId,
						collectAddressContactName:  address.contactName,
						collectAddressCellNum: address.cellNum,
						collectAddressStreet: address.street,
						collectAddressFullAddr: address.fullAddr,
						collectAddressPostCode: address.postalCode,
						showCollectMailboxNum: address.mailboxNumRule&&address.mailboxNumRule.showCollectMailboxNum
					})
				} else if (!address) {
					address = {}
					address['provinceId'] = ''
					address['cityId'] = ''
					address['countyId'] = ''
					address['contactName'] = ''
					address['cellNum'] = ''
					address['street'] = ''
					address['fullAddr'] = ''
					address['postalCode'] = ''

					this.setData({
						collectAddressAll: address,
						collectAddressProvinceId: address.provinceId,
						collectAddressCityId: address.cityId, 
						collectAddressCountyId: address.countyId,
						collectAddressContactName: address.contactName,
						collectAddressCellNum: address.cellNum,
						collectAddressStreet: address.street,
						collectAddressFullAddr: address.fullAddr,
						collectAddressPostCode: address.postalCode,
						showCollectMailboxNum: address.mailboxNumRule&&address.mailboxNumRule.showCollectMailboxNum
					})
				}
			} 

			if (mailType == 'send') { //寄
				let addressCurees = {};
				if (address) {
					addressCurees = address
					// if (this.data.collectAddressAll&&this.data.collectAddressAll.id == addressCurees.id) {
					// 	app.errorToast('不能和收件地址相同')
					// 	return;
					// }
				} else {
					addressCurees['provinceId'] = ''
					addressCurees['cityId'] = ''
					addressCurees['countyId'] = ''
					addressCurees['contactName'] = ''
					addressCurees['cellNum'] = ''
					addressCurees['street'] = ''
					addressCurees['fullAddr'] = ''
					addressCurees['postalCode'] = ''
				}

				if (addressCurees.mailboxNumRule&&addressCurees.mailboxNumRule.showSendMailboxNum == 1) {
					this.setData({
						sendAddressMailboxNum: addressCurees.mailboxNum
					})
				} else {
					this.setData({
						sendAddressMailboxNum: ''
					})
				}
		
				this.setData({
					sendAddressAll: addressCurees,
					sendAddressProvinceId: addressCurees.provinceId, 
					sendAddressCityId: addressCurees.cityId,
					sendAddressCountyId: addressCurees.countyId,
					sendAddressContactName: addressCurees.contactName,
					sendAddressCellNum: addressCurees.cellNum,
					sendAddressStreet: addressCurees.street,
					sendAddressFullAddr: addressCurees.fullAddr,
					sendAddressPostCode: addressCurees.postalCode,
					showSendMailboxNum: addressCurees.mailboxNumRule&&addressCurees.mailboxNumRule.showSendMailboxNum
				})
			} 
	},

	onLoad(options) {
		let that = this;
		app.getOpenIdRender((num,openId) => {
			//that.getAdvertisement();  //广告
			that.getOptionsParam(options); //获取扫码参数
			if (!app.getStorageSync('tagSign')) {
				that.getAddressDefault((data) => { //首次取默认寄件地址
					if (data.mailboxNumRule&&data.mailboxNumRule.showSendMailboxNum == 1) {
						this.setData({
							sendAddressMailboxNum: data.mailboxNum
						})
					} else {
						this.setData({
							sendAddressMailboxNum: ''
						})
					}
					that.setData({
						sendAddressAll: data,
						sendAddressProvinceId: data.provinceId, 
						sendAddressCityId: data.cityId,
						sendAddressCountyId: data.countyId,
						sendAddressContactName: data.contactName,
						sendAddressCellNum: data.cellNum,
						sendAddressStreet: data.street,
						sendAddressFullAddr: data.fullAddr,
						sendAddressPostCode: data.postalCode,

					})
				})
			}
		})
	},

	onShow() {
		let that = this;
		app.getOrderNum()
		app.getOpenIdRender((num,openId) => {
			that.setData({
				num: num
			})
			if (app.getStorageSync('paySuccessSign')) { //提交成功回复默认值
				that.setData({
					sendTypeName: '普通快递', //寄送类型
					sendType: 1,
					goodsTypeName: '文件',
					goodsType: '01',
					leaveText: '', //留言
					mailType: '',  //寄递类型 *区分寄或者收
				
					//收
					collectAddressProvinceId: '',
					collectAddressCityId: '', 
					collectAddressCountyId: '',
					collectAddressContactName:  '',
					collectAddressCellNum: '',
					collectAddressStreet: '',
					collectAddressFullAddr: '',
					collectAddressMailboxNum: '',
					collectAddressPostCode: '',
					showCollectMailboxNum: ''
				})
				that.getAddressDefault((data) => { //首默认寄件地址
					if (data.mailboxNumRule&&data.mailboxNumRule.showSendMailboxNum == 1) {
						this.setData({
							sendAddressMailboxNum: data.mailboxNum
						})
					} else {
						this.setData({
							sendAddressMailboxNum: ''
						})
					}
					that.setData({
						sendAddressAll: data,
						sendAddressProvinceId: data.provinceId, 
						sendAddressCityId: data.cityId,
						sendAddressCountyId: data.countyId,
						sendAddressContactName: data.contactName,
						sendAddressCellNum: data.cellNum,
						sendAddressStreet: data.street,
						sendAddressFullAddr: data.fullAddr,
						sendAddressPostCode: data.postalCode,
					})
				})
			}
			let page = app.getStorageSync(app.globalData.cacheData);
			that.setData(Object.assign({},page,{num: num}));
			that.setAddress() //选择地址列表地址赋值
		})
	},
	
	//底部切换页面方法
	toUrl(e) {
		let url = e.currentTarget.dataset.url;
		if(url!='/pages/handle/handle') { //点击不是当前页面
			app.setStorageSync(app.globalData.cacheData,this.data);
			if (url == '') {
				//develop（开发版），trial（体验版），release（正式版）
				let res = {
					appid: app.globalData.appid,
					path: '',
					envVersion: app.globalData.envVersion
				}
				app.crossToUrl(res)
			} else {
				app.redirectTo({url: url})
			}
		}
	},

	cacheData() {
		app.setStorageSync(app.globalData.cacheData,Object.assign({},this.data,{ popErrorMsg: '' },{errorScrollIntoViewName: ''},
			{errorFocusName:''}, {isCanScroll: true},{isShowModal: false})); //保存状态在缓存
		app.removeStorageSync('paySuccessSign')
		app.removeStorageSync('tagSign')
	},

	onHide() {
		this.cacheData()
	},

	onUnload() {
		this.cacheData()
	},

	getAddressDefault(callBack) {
		let that = this;
		let advertOpt = {   //默认地址
			url: app.globalData.host + "/wx/ad/q/default.ajax",
			data: {},
			sucFn:(result) => {//result.body
				typeof(callBack) == 'function'&&callBack(result.body)
			}
		};
		app.ajax(advertOpt);
	},

	//确认提交按钮
	formSubmit(e) {
		let { leaveText, expressNbr, sendType, goodsType, needInvoice,
			sendAddressProvinceId, sendAddressCityId, sendAddressCountyId, sendAddressContactName,
			sendAddressCellNum, sendAddressStreet, sendAddressFullAddr, sendAddressMailboxNum, sendAddressPostCode,

			collectAddressProvinceId, collectAddressCityId, collectAddressCountyId, collectAddressContactName,
			collectAddressCellNum, collectAddressStreet, collectAddressFullAddr, collectAddressMailboxNum, collectAddressPostCode
			} = this.data,
			that = this;
		let flag = app.check([
			{
				value: sendAddressContactName,
				fn: (value) => {
					if (!value) {
						app.errorToast(FormCheckRule.sendAddressNullMessage);
						return false;
					} else {
						return true;
					}
				}
			}, {
				value: collectAddressContactName,
				fn: (value) => {
					if (!value) {
						app.errorToast(FormCheckRule.collectAddressNullMessage);
						return false;
					} else {
						return true;
					}
				}
			}, {
				value: needInvoice,
				fn: (value) => {
					if (value == '') {
						let hint = sendType == 1?FormCheckRule.checkService:FormCheckRule.hkCheckService
						app.errorToast(hint);
						return false;
					} else {
						return true;
					}
				}
			},
		]);
		if (!flag) {
			return false;
		}

		if(!app.globalData.isAuthSuccess){
            app.toastAuthFailModal();
            return false;
		}
		
		let platform = '';
		if (app.isAndroid()) {
			platform = 'android'
        } else {
			platform = 'iPhone'
		}
		
		// return
		let formResult = {
			"payType": 0,//到付
			'platform': platform,
			'formId': e.detail.formId,
			"mailingAddressRange": sendType,
			"postUserName": sendAddressContactName || '', 
			"goodType": goodsType,
			"channelId": "wx",
			//寄
			"address.provinceId": sendAddressProvinceId || '', 
			"address.cityId": sendAddressCityId || '',
			"address.countyId": sendAddressCountyId || '',
			"address.contactName": sendAddressContactName || '',
			"address.cellNum": sendAddressCellNum || '',
			"address.street": sendAddressStreet || '',
			"address.fullAddr": sendAddressFullAddr || '',
			"address.mailboxNum": sendAddressMailboxNum || '', //邮筒号
			"address.postCode": sendAddressPostCode || '',
			//收
			"collectOrderAddress.provinceId": collectAddressProvinceId || '',
			"collectOrderAddress.cityId": collectAddressCityId || '', 
			"collectOrderAddress.countyId": collectAddressCountyId || '',
			"collectOrderAddress.contactName": collectAddressContactName || '',
			"collectOrderAddress.cellNum": collectAddressCellNum || '',
			"collectOrderAddress.street": collectAddressStreet || '',
			"collectOrderAddress.fullAddr": collectAddressFullAddr || '',
			"collectOrderAddress.mailboxNum": collectAddressMailboxNum || '', //邮筒号
			"collectOrderAddress.postCode": collectAddressPostCode || '', 

			"otherExplain": leaveText || '',  //留言
			"expressNbr": expressNbr || '' //智能面单 13位   下过单 1117825901113
		};
		let { sendTypeName, goodsTypeName, showSendMailboxNum, showCollectMailboxNum } = this.data;

		let opt = {
			url: app.globalData.host+"/wx/sd/handlingZn.ajax",
			data: formResult,
			sucFn: (result) => { //0 没有添加  1添加过-弹框
				if (result.body.expressNbrIsUsed == 1) {
					that.setData({
						isSHowWaybillMask: true,
						isShowFootNav: false,  //底部导航菜单
					})
					return;
				}
				let orderId = result.body.orderIds[0].id;
				formResult['orderId'] = orderId
				formResult['sendTypeName'] = sendTypeName
				formResult['goodsTypeName'] = goodsTypeName 
				formResult['timeDiffer'] = result.body.timeDiffer
				formResult['showSendMailboxNum'] = showSendMailboxNum
				formResult['showCollectMailboxNum'] = showCollectMailboxNum
				app.setStorageSync(app.globalData.cacheOrderPay, formResult);
				app.navigateTo({url:'../payment/payment?orderId=' + orderId})
			}
		};
		app.ajax(opt);
	},

	//说明内容
	agreeTap(e) {
		let isNoticeShow='';
		switch (this.data.sendType) {
			case 1:
				isNoticeShow = 'ordinary'
				break;
			case 2:
				isNoticeShow = 'hk'
				break;
		}
		app.navigateTo({url:'../agreement/agreement?isNoticeShow='+ isNoticeShow})
	},

	//点击邮寄类型显示类别列表
	sendTypeSelection(e) {
		this.setData({
			isCanScroll:false,
			isShowSendTypeList: true,
			isShowFootNav: false
		});
	},

  //点击mask隐藏旅游邮寄类别列表
	hideSendTypeSelection() {
		this.setData({
			isCanScroll: true,
			isShowSendTypeList: false,
			isShowFootNav: true
		});
	},

	//选择邮寄类型
	selectSendType(e) {
		this.setData({
			sendType: e.target.dataset.type,
			sendTypeName: e.target.dataset.name
		})
	},

	//取消按钮
	cancelSendTypeSelection() {
		this.setData({
			sendType: -1,
			isCanScroll: true,
			isShowSendTypeList: false,
			isShowFootNav: true,
		});
	},

	//start
	//点击商品类型显示类别列表
	goodsTypeSelection(e) {
		this.setData({
			isCanScroll:false,
			isShowGoodsTypeList: true,
			isShowFootNav: false
		})
	},

  //点击mask隐藏旅游邮寄类别列表
	hideGoodsTypeSelection() {
		this.setData({
			isCanScroll: true,
			isShowGoodsTypeList: false,
			isShowFootNav: true
		});
	},

	//选择邮寄类型
	selectGoodsType(e) {
		this.setData({
			goodsType: e.target.dataset.type,
			goodsTypeName: e.target.dataset.name
		})
	},

	//取消按钮
	cancelGoodsTypeSelection() {
		this.setData({
			sendType: -1,
			isCanScroll: true,
			isShowGoodsTypeList: false,
			isShowFootNav: true,
		});
	}
	//end
});
